package org.forex.impl.engine;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;

import org.forex.impl.property.MainConfig;
import org.forex.vo.Instrument;
import org.forex.vo.Order;
import org.forex.vo.Prices;

public class InstrumentTrade {

	private Instrument instrument;
	private List<Prices> prices;
	private Order order; 
	
	public InstrumentTrade(Instrument ins) {
		this.setInstrument(ins);
	}

	public void addPrice(Prices p) {
		getPrices().add(p);
	}
	
	public Instrument getInstrument() {
		return instrument;
	}

	public void setInstrument(Instrument instrument) {
		this.instrument = instrument;
	}

	public List<Prices> getPrices() {
		if(prices==null)
			prices=new LinkedList<Prices>();
		return prices;
	}

	public void setPrices(List<Prices> prices) {
		this.prices = prices;
	}

	public String getTrend() {

		final PriceTrend pt=new PriceTrend();
		
		pt.price=getPrices().get(0).getInstruments().get(0).getBid();
		
		for(int i=1;i<5;i++){
			
			double bid=getPrices().get(i).getInstruments().get(0).getBid();
			
			double difference=getDouble(pt.price-bid);
			
			pt.price=bid;			
			
			if(difference==0.0)
				continue;
			
			if(difference > 0){
				//il prezzo sta scendendo
				pt.trend--;
				pt.difference+=difference;
			}else{
				if(difference<0){
					//il prezzo sta crescendo
					pt.trend++;
					pt.difference+=difference;
				}						
			}
			
		}
		
		return calculateTrend(pt);
	}
	
	public String calculateTrend(PriceTrend pt){
		
		if(Math.abs(pt.difference) < 0.02)
			return MainConfig.config().trendNone();
		
		if(pt.difference > 0)
			return MainConfig.config().trendSell();
		if(pt.difference < 0)
			return MainConfig.config().trendBuy();
		
		return MainConfig.config().trendNone();		
	}
	
	public Order getOrder() {
		return order;
	}

	public void setOrderAndStartCheck(Order order) {
		this.order = order;
		
	}
	
	public double getDouble(double d){
		return new BigDecimal(d).setScale(3, BigDecimal.ROUND_DOWN).doubleValue();
	}

	public static class PriceTrend{
		
		public double price=0.0;
		
		public int trend=0;
		
		public double difference=0.0;
	}
	
	public static class TrendOrder implements Callable<String>{

		@Override
		public String call() throws Exception {
			return null;	
		}
		
	}

}
